import { getLang } from './auth'
const second = 1000;
const minute = 60 * second;
const hour = 60 * minute;
const day = 24 * hour;
const month = 30 * day;
const year = 365 * day;

const lang = getLang() || "ZH"
const langObj = {
  ZH:{
    gangang:"刚刚",
    jijiang:"即将",
    before:"前",
    year:"年",
    month:"个月",
    day:"天",
    hour:"小时",
    minute:"分钟"
  },
  EN:{
    ganggang:"Just a moment",
    jijiang:"Right now",
    before:" ago ",
    month:" months ",
    day:" days ",
    hour:" hours ",
    minute:" minutes "
  }
}
function isInvalid(date) {
  return date.toString() === "Invalid Date";
}

export function parseInputTime(any) {
  const then = new Date(typeof any === "number" ? any * 1000 : any);
  return isInvalid(then) ? "" : then;
}

export function defaultGetPrefix(diff) {
  return diff >= 0 ? "" : "还有";
}

export function defaultGetSuffix(diff) {
  return diff >= 0 ? langObj[lang].before : "";
}

export function getRelativeTimeString(
  any,
  {
    accurate = 1000,
    getPrefix = defaultGetPrefix,
    getSuffix = defaultGetSuffix
  } = {}
) {
  const then = parseInputTime(any);
  if (!then) {
    return "";
  }
  const now = new Date();
  // backend 精确到秒
  const diff = Math.round((Number(now) - Number(then)) / accurate) * 1000;
  const absDiff = Math.abs(diff);
  if (absDiff < minute) {
    return diff >= 0 ? langObj[lang].gangang : langObj[lang].jijiang;
  }
  let diffString;
  if (absDiff < hour) {
    diffString = `${Math.floor(absDiff / minute)}${langObj[lang].minute}`;
  } else if (absDiff < day) {
    diffString = `${Math.floor(absDiff / hour)}${langObj[lang].hour}`;
  } else if (absDiff < month) {
    diffString = `${Math.floor(absDiff / day)}${langObj[lang].day}`;
  } else if (absDiff < year) {
    diffString = `${Math.floor(absDiff / month)}${langObj[lang].month}`;
  } else {
    diffString = `${Math.floor(absDiff / year)}${langObj[lang].year}`;
  }
  return `${getPrefix(diff)}${diffString}${getSuffix(diff)}`;
}